package com.pengtu.gsj.service.impl.check.yh.equipment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.check.CheckTable;
import com.pengtu.gsj.entity.yh.Training;
import com.pengtu.gsj.service.check.CheckTableService;
import com.pengtu.gsj.service.check.DownService;
import com.pengtu.gsj.service.check.yh.equipment.TechnicalTrainingService;
import com.pengtu.gsj.service.system.OrganizationService;
import com.pengtu.gsj.service.system.SystemManageService;
import com.pengtu.gsj.service.yh.TrainingService;
import com.pengtu.gsj.utils.MathsUtils;

@Service
@Transactional
public class TechnicalTrainingServiceImpl implements TechnicalTrainingService {
	
	@Autowired
	private CheckTableService checkTableService;
	@Autowired
	private SystemManageService systemManageService;
	@Autowired
	private DownService downService;
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private TrainingService trainingService;

	@Override
	public Map<String, Object> getCheckContent(String startTime,
			String endTime, CheckTable checkTable, String tag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Object> values = new ArrayList<Object>();
		List<Training> trains = new ArrayList<Training>();
		
		JSONObject jsonObject = JSONObject.parseObject(checkTable.getRetrieval());
		double yearFull = Double.parseDouble((String)jsonObject.get("yearFull"));
		double yearPart = Double.parseDouble((String)jsonObject.get("yearPart"));
		
		//查询所有相关的附件
		List<Attachment> list = systemManageService.getAllCheckAttachments(startTime, endTime, tag);
		//查询国省检时间段内所有的培训记录数据  数据的长度就是培训的次数
		trains = trainingService.getCheckTrains(startTime, endTime);
		double total =0; //检查得分
		double percentage =0; //系统完善度
		double tableFull = yearFull;
		int totalPerson = 0;
		
		if (trains.size() > 0) {
			total = trains.size() * yearPart;
			//不能超过满分
			if (total > yearFull ) {
				total = yearFull;
			}
			percentage = MathsUtils.divDouble(total*100, yearFull, 2);
		}
		//统计总培训人数
		for (Training training : trains) {
			totalPerson += training.getPersonCount();
		}
		//需要更新数据
		values.add("true");
		checkTableService.updateCheckTable(checkTable, percentage, total, tableFull, values);
		map.put("att", list);
		map.put("score", checkTable.getTestFull());
		map.put("trains", trains);
		map.put("count", trains.size());
		map.put("totalPerson", totalPerson);
		map.put("checkTable", checkTable);
		return map;
	}

}
